{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 06 网格搜索和更多kNN中的超参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from sklearn import datasets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "digits = datasets.load_digits()\n",
    "X = digits.data\n",
    "y = digits.target"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=666)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "0.9916666666666667"
     },
     "metadata": {},
     "execution_count": 4
    }
   ],
   "source": [
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "\n",
    "sk_knn_clf = KNeighborsClassifier(n_neighbors=4, weights=\"uniform\")\n",
    "sk_knn_clf.fit(X_train, y_train)\n",
    "sk_knn_clf.score(X_test, y_test)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Grid Search\n",
    "scikit learn中的超参数的网格搜索方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 所有想搜索的参数，键和参数的范围\n",
    "# uniform的时候不需要对明可夫斯基距离进行搜索\n",
    "param_grid = [\n",
    "    {\n",
    "        'weights': ['uniform'], \n",
    "        'n_neighbors': [i for i in range(1, 11)]\n",
    "    },\n",
    "    {\n",
    "        'weights': ['distance'],\n",
    "        'n_neighbors': [i for i in range(1, 11)], \n",
    "        'p': [i for i in range(1, 6)]\n",
    "    },\n",
    "    {\n",
    "        'metric': ['chebyshev', 'seuclidean', 'seuclidean'],\n",
    "        'n_neighbors': [i for i in range(1, 6)]\n",
    "    }\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "knn_clf = KNeighborsClassifier()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 网格搜索就是为了决定更好的模型，所以在model_selection中\n",
    "from sklearn.model_selection import GridSearchCV\n",
    "\n",
    "# 对哪一个分类器进行网格搜索，传入网格搜索相应的参数\n",
    "grid_search = GridSearchCV(knn_clf, param_grid)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "Wall time: 1min 4s\n"
    },
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "GridSearchCV(cv=None, error_score=nan,\n             estimator=KNeighborsClassifier(algorithm='auto', leaf_size=30,\n                                            metric='minkowski',\n                                            metric_params=None, n_jobs=None,\n                                            n_neighbors=5, p=2,\n                                            weights='uniform'),\n             iid='deprecated', n_jobs=None,\n             param_grid=[{'n_neighbors': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n                          'weights': ['uniform']},\n                         {'n_neighbors': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n                          'p': [1, 2, 3, 4, 5], 'weights': ['distance']}],\n             pre_dispatch='2*n_jobs', refit=True, return_train_score=False,\n             scoring=None, verbose=0)"
     },
     "metadata": {},
     "execution_count": 8
    }
   ],
   "source": [
    "%%time\n",
    "grid_search.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',\n                     metric_params=None, n_jobs=None, n_neighbors=1, p=2,\n                     weights='uniform')"
     },
     "metadata": {},
     "execution_count": 9
    }
   ],
   "source": [
    "# 返回最佳分类器的最佳参数\n",
    "# 可能和手动网格搜索的参数不一样\n",
    "# 因为使用了cross validation，比train-test-split准确度更高\n",
    "grid_search.best_estimator_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "0.9860820751064653\n{'n_neighbors': 1, 'weights': 'uniform'}\n"
    }
   ],
   "source": [
    "# 最佳分数\n",
    "# 不是用户传入的参数，而是自己经过计算得到的参数在后面加上一个下划线\n",
    "print(grid_search.best_score_)\n",
    "print(grid_search.best_params_)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "0.9833333333333333"
     },
     "metadata": {},
     "execution_count": 14
    }
   ],
   "source": [
    "# 返回最佳参数的分类器\n",
    "knn_clf = grid_search.best_estimator_\n",
    "knn_clf.score(X_test, y_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "Fitting 5 folds for each of 75 candidates, totalling 375 fits\n[Parallel(n_jobs=-1)]: Using backend LokyBackend with 8 concurrent workers.\n[Parallel(n_jobs=-1)]: Done  25 tasks      | elapsed:    1.7s\n[Parallel(n_jobs=-1)]: Done 236 tasks      | elapsed:   11.0s\n0.9860820751064653\n{'n_neighbors': 1, 'weights': 'uniform'}\nWall time: 14.7 s\n[Parallel(n_jobs=-1)]: Done 375 out of 375 | elapsed:   14.6s finished\n"
    }
   ],
   "source": [
    "%%time\n",
    "# n_jobs指定核数。-1是使用所有核数\n",
    "# verbose是搜索中进行输出。整数越大信息越详细，一般2就OK\n",
    "grid_search = GridSearchCV(knn_clf, param_grid, n_jobs=-1, verbose=2)\n",
    "grid_search.fit(X_train, y_train)\n",
    "print(grid_search.best_score_)\n",
    "print(grid_search.best_params_)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 其他超参数\n",
    "\n",
    "metrics: [http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.DistanceMetric.html](http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.DistanceMetric.html)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.6.8 64-bit ('anaconda': conda)",
   "language": "python",
   "name": "python36864bitanacondaconda085db2e8b14649f4b32196068f7124e9"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.7-final"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}